<template>
  <div class="admin--page-content">
    <div class="admin--sub--table--title">
      <p>{{ areaName ? `${areaName} 낚시어선 / 낚시터` : "낚시어선 / 낚시터" }}</p>
      <div class="sub--table--info">
        <span>🎣 낚시터 {{ fishingCount }}</span>
        <span>🚢 낚시어선 {{ onboardCount }}</span>
      </div>
    </div>

    <div class="admin--table-wrapper">
      <table class="admin--table">
        <thead>
          <tr>
            <th style="width: 80px;">번호</th>
            <th style="width: 180px;">구분</th>
            <th>이름</th>
            <th>주소</th>
            <th>상태</th>
            <th style="width: 120px;">등록일</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="isLoading">
            <td colspan="6" class="admin--table-loading">데이터를 불러오는 중...</td>
          </tr>
          <tr v-else-if="!places || places.length === 0">
            <td colspan="6" class="admin--table-empty">해당 지역에 등록된 낚시어선/낚시터가 없습니다.</td>
          </tr>
          <tr
            v-else
            v-for="(p, index) in places"
            :key="p.place_type + '-' + p.id"
            class="admin--table-row-clickable"
            @click="goToPlace(p)"
          >
            <td class="date">{{ totalCount - ((currentPage - 1) * perPage + index) }}</td>
            <td>
              <span :class="['admin--badge', p.place_type === 'onboard' ? 'admin--badge-active' : 'admin--badge-html']">
                {{ p.place_type === "onboard" ? "낚시어선" : "낚시터" }}
              </span>
            </td>
            <td class="admin--table-title">{{ p.name }}</td>
            <td>{{ p.address || "-" }}</td>
            <td>
              <span :class="['admin--badge', p.status_YN === 'Y' ? 'admin--badge-active' : 'admin--badge-ended']">
                {{ p.status_YN === "Y" ? "사용중" : "미사용" }}
              </span>
            </td>
            <td class="date">{{ formatDate(p.created_at) }}</td>
          </tr>
        </tbody>
      </table>
    </div>

    <div class="admin--place--btn--wrap">
      <!-- 버튼 영역 -->
      <div class="admin--form-actions">
        <button type="button" class="admin--btn" @click="goBack">
          ← 지역 상세로
        </button>
      </div>
      <!-- 페이지네이션 -->
      <div v-if="totalPages > 1" class="admin--pagination">
        <button
          v-if="totalPages > 2"
          class="admin--pagination-btn"
          :disabled="currentPage === 1"
          @click="changePage(1)"
          title="처음"
        >◀◀</button>
        <button
          class="admin--pagination-btn"
          :disabled="currentPage === 1"
          @click="changePage(currentPage - 1)"
          title="이전"
        >◀</button>
        <button
          v-for="page in visiblePages"
          :key="page"
          class="admin--pagination-btn"
          :class="{ 'is-active': page === currentPage }"
          @click="changePage(page)"
        >{{ page }}</button>
        <button
          class="admin--pagination-btn"
          :disabled="currentPage === totalPages"
          @click="changePage(currentPage + 1)"
          title="다음"
        >▶</button>
        <button
          v-if="totalPages > 2"
          class="admin--pagination-btn"
          :disabled="currentPage === totalPages"
          @click="changePage(totalPages)"
          title="끝"
        >▶▶</button>
      </div>
    </div>
  </div>
</template>

<script setup>
  import { ref, computed, onMounted } from "vue";
  import { useRoute, useRouter } from "vue-router";

  definePageMeta({
    layout: "admin",
    middleware: ["auth"],
  });

  const route = useRoute();
  const router = useRouter();
  const { get } = useApi();

  const areaId = route.params.id;

  const isLoading = ref(false);
  const places = ref([]);
  const areaName = ref("");
  const onboardCount = ref(0);
  const fishingCount = ref(0);

  const currentPage = ref(1);
  const perPage = ref(10);
  const totalCount = ref(0);
  const totalPages = ref(0);

  // 페이지네이션 표시 페이지 번호
  const visiblePages = computed(() => {
    const pages = [];
    const maxVisible = 5;
    let start = Math.max(1, currentPage.value - Math.floor(maxVisible / 2));
    let end = Math.min(totalPages.value, start + maxVisible - 1);
    if (end - start < maxVisible - 1) start = Math.max(1, end - maxVisible + 1);
    for (let i = start; i <= end; i++) pages.push(i);
    return pages;
  });

  // 데이터 로드
  const loadPlaces = async () => {
    isLoading.value = true;
    const { data, error } = await get(`/area/${areaId}/places`, {
      params: { page: currentPage.value, per_page: perPage.value },
    });
    if (!error && data?.success && data?.data) {
      places.value = data.data.items || [];
      areaName.value = data.data.area_name || "";
      onboardCount.value = data.data.onboard_count || 0;
      fishingCount.value = data.data.fishing_count || 0;
      totalCount.value = data.data.total || 0;
      totalPages.value = data.data.total_pages || 0;
    }
    isLoading.value = false;
  };

  // 페이지 변경
  const changePage = (page) => {
    if (page < 1 || page > totalPages.value) return;
    currentPage.value = page;
    loadPlaces();
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  // 이동
  const goToPlace = (p) => {
    if (p.place_type === "onboard") {
      router.push(`/site-manager/onboard/detail/${p.id}`);
    } else if (p.place_type === "fishing") {
      router.push(`/site-manager/fishing/detail/${p.id}`);
    }
  };
  const goBack = () => router.push(`/site-manager/area/detail/${areaId}`);

  // 날짜만
  const formatDate = (dateString) => {
    if (!dateString) return "-";
    const date = new Date(dateString.replace(" ", "T"));
    if (isNaN(date.getTime())) return dateString;
    return date.toLocaleDateString("ko-KR", { year: "numeric", month: "2-digit", day: "2-digit" });
  };

  onMounted(() => {
    loadPlaces();
  });
</script>
